package com.cs.sso.service.impl;

import com.cs.sso.dbo.LoginLog;
import com.cs.sso.repository.LoginLogRepository;
import com.cs.sso.service.LoginLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class LoginLogServiceImpl implements LoginLogService {
    @Autowired
    private LoginLogRepository loginLogRepository;

    @Override
    public void writeSuccessLog(String username) {
        LoginLog loginLog = new LoginLog();
        loginLog.setUsername(username);
        loginLog.setIsError("OK");
        loginLog.setLoginTime(new Date());
        loginLogRepository.save(loginLog);
    }

    @Override
    public void writeErrorLog(String username) {
        LoginLog loginLog = new LoginLog();
        loginLog.setUsername(username);
        loginLog.setIsError("ERR");
        loginLog.setLoginTime(new Date());
        loginLogRepository.save(loginLog);
    }

    @Override
    public int currentErrorTimes(String username) {
        List<LoginLog> loginLogList = loginLogRepository.findTop10ByUsername(username, Sort.by(Sort.Direction.DESC, "loginTime"));
        int errorTimes = 0;
        for (LoginLog loginLog : loginLogList) {
            if ("OK".equals(loginLog.getIsError()) || "RESET".equals(loginLog.getIsError())) {
                break;
            } else if ("ERR".equals(loginLog.getIsError())){
                errorTimes++;
            } else {
                log.error("{}的登录记录出现奇怪状态:{}", username, loginLog.getIsError());
            }
        }
        return errorTimes;
    }

    @Override
    public void writeResetLog(String username) {
        LoginLog loginLog = new LoginLog();
        loginLog.setUsername(username);
        loginLog.setIsError("RESET");
        loginLog.setLoginTime(new Date());
        loginLogRepository.save(loginLog);
    }
}
